package com.yunshangwoniu.core.ValidateCodeService;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.yunshangwoniu.core.utils.RequestUtils;

public class ValidateCodeService
{
	private Logger logger = Logger.getLogger(this.getClass());
	private Map<String, Object> validateCodeCache = new HashMap<String, Object>();

	/**
	 * 获得验证码
	 * @param request
	 * @return
	 */
	public String getValidateCode(HttpServletRequest request)
	{
		String validateCode = randomStringProvider();
		String userIp = RequestUtils.getIp(request);
		validateCodeCache.put(userIp, validateCode);
		logger.debug("---------ip:"+userIp+"--------code:"+validateCode);
		
		return validateCode;
	}
	
	/**
	 * 验证验证码是否正确
	 * @param request
	 * @param validateCode
	 * @return
	 */
	public String validate(HttpServletRequest request,String validateCode)
	{
		return validateCode.equalsIgnoreCase((String)validateCodeCache.get(RequestUtils.getIp(request)))?validateCode:getValidateCode(request);	//如果存在则返回传入的，如果不存在则重新生成
	}

	/**
	 * 登录成功一定要清除缓存中的验证码
	 * @param request
	 */
	public void clear(HttpServletRequest request)
	{
		validateCodeCache.remove(RequestUtils.getIp(request));
	}
	/**
	 * 4位随机数生成器（验证码生成器）
	 * @return
	 */
	private String randomStringProvider()
	{
		String str = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
		String str2[] = str.split(",");
		StringBuilder sb = new StringBuilder();
		while(sb.length()<4)
		{
			Random random = new Random();
			int index = random.nextInt(62);
			sb.append(str2[index]);
		}
		
		return sb.toString();
	}

	
	public static void main(String args[])
	{
		System.out.println(new ValidateCodeService().randomStringProvider());
	}
	
}
